import React, { useRef, useEffect } from 'react';
import { useFrame, useThree } from '@react-three/fiber';
import { PointerLockControls } from '@react-three/drei';
import * as THREE from 'three';

interface FirstPersonControlsProps {
  enabled?: boolean;
  walkSpeed?: number;
  runSpeed?: number;
  boundaryRadius?: number;
  fixedHeight?: number;
}

export const FirstPersonControls: React.FC<FirstPersonControlsProps> = ({
  enabled = true,
  walkSpeed = 6,
  runSpeed = 12,
  boundaryRadius = 18,
  fixedHeight = 1.7  // 固定高度，模拟人眼高度
}) => {
  const { camera, gl } = useThree();
  const controlsRef = useRef<any>(null);
  
  // Movement state
  const movement = useRef({
    forward: false,
    backward: false,
    left: false,
    right: false,
    running: false
  });

  const velocity = useRef(new THREE.Vector3());
  const direction = useRef(new THREE.Vector3());

  useEffect(() => {
    if (!enabled) return;

    const handleKeyDown = (event: KeyboardEvent) => {
      switch (event.code) {
        case 'KeyW':
        case 'ArrowUp':
          movement.current.forward = true;
          break;
        case 'KeyS':
        case 'ArrowDown':
          movement.current.backward = true;
          break;
        case 'KeyA':
        case 'ArrowLeft':
          movement.current.left = true; // 修复：A键应该向左
          break;
        case 'KeyD':
        case 'ArrowRight':
          movement.current.right = true; // 修复：D键应该向右
          break;
        case 'ShiftLeft':
        case 'ShiftRight':
          movement.current.running = true; // Shift跑步
          break;
      }
    };

    const handleKeyUp = (event: KeyboardEvent) => {
      switch (event.code) {
        case 'KeyW':
        case 'ArrowUp':
          movement.current.forward = false;
          break;
        case 'KeyS':
        case 'ArrowDown':
          movement.current.backward = false;
          break;
        case 'KeyA':
        case 'ArrowLeft':
          movement.current.left = false;
          break;
        case 'KeyD':
        case 'ArrowRight':
          movement.current.right = false;
          break;
        case 'ShiftLeft':
        case 'ShiftRight':
          movement.current.running = false;
          break;
      }
    };

    document.addEventListener('keydown', handleKeyDown);
    document.addEventListener('keyup', handleKeyUp);

    return () => {
      document.removeEventListener('keydown', handleKeyDown);
      document.removeEventListener('keyup', handleKeyUp);
    };
  }, [enabled]);

  useFrame((state, delta) => {
    if (!controlsRef.current || !enabled) return;

    // 选择速度（跑步或走路）
    const currentSpeed = movement.current.running && movement.current.forward 
      ? runSpeed 
      : walkSpeed;

    // Smooth velocity decay
    velocity.current.x -= velocity.current.x * 8.0 * delta;
    velocity.current.z -= velocity.current.z * 8.0 * delta;
    // 移除Y轴速度控制

    // Calculate movement direction - 修复左右方向
    direction.current.z = Number(movement.current.forward) - Number(movement.current.backward);
    direction.current.x = Number(movement.current.left) - Number(movement.current.right); // 修复：左负右正
    direction.current.y = 0; // 禁用垂直移动
    direction.current.normalize();

    // Apply movement forces
    if (movement.current.forward || movement.current.backward) {
      velocity.current.z -= direction.current.z * currentSpeed * delta;
    }
    if (movement.current.left || movement.current.right) {
      velocity.current.x -= direction.current.x * currentSpeed * delta;
    }

    // Get camera object
    const object = controlsRef.current.getObject();
    if (object) {
      // Apply horizontal movement only
      object.translateX(velocity.current.x * delta);
      object.translateZ(velocity.current.z * delta);

      // 强制固定高度
      object.position.y = fixedHeight;

      // 室内咖啡厅的边界检测 - 矩形房间边界
      const position = object.position;
      const roomBounds = {
        minX: -boundaryRadius + 1,
        maxX: boundaryRadius - 1,
        minZ: -boundaryRadius + 1,
        maxZ: boundaryRadius - 1
      };
      
      // 检查是否超出房间边界
      if (position.x < roomBounds.minX) position.x = roomBounds.minX;
      if (position.x > roomBounds.maxX) position.x = roomBounds.maxX;
      if (position.z < roomBounds.minZ) position.z = roomBounds.minZ;
      if (position.z > roomBounds.maxZ) position.z = roomBounds.maxZ;

      // 咖啡吧台碰撞检测 - 避免走进吧台
      const barBounds = {
        minX: -6, maxX: 6,
        minZ: boundaryRadius - 6, maxZ: boundaryRadius - 2
      };

      if (position.x > barBounds.minX && position.x < barBounds.maxX &&
          position.z > barBounds.minZ && position.z < barBounds.maxZ) {
        
        // 将玩家推出吧台区域
        const centerX = (barBounds.minX + barBounds.maxX) / 2;
        const centerZ = (barBounds.minZ + barBounds.maxZ) / 2;
        
        const dx = position.x - centerX;
        const dz = position.z - centerZ;
        
        if (Math.abs(dx) > Math.abs(dz)) {
          position.x = dx > 0 ? barBounds.maxX + 0.5 : barBounds.minX - 0.5;
        } else {
          position.z = dz > 0 ? barBounds.maxZ + 0.5 : barBounds.minZ - 0.5;
        }
        
        velocity.current.x = 0;
        velocity.current.z = 0;
      }
    }
  });

  if (!enabled) return null;

  return (
    <PointerLockControls 
      ref={controlsRef}
      args={[camera, gl.domElement]}
      selector="#root"
    />
  );
};